/*
 * $HeadURL:  $
 *
 * Copyright (c) 2007 Drutt Corporation, all rights reserved.
 *
 */
package homework.james.xiao.client;

import homework.james.xiao.bean.Admin;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class AdminClient {
	public static String HOST = "localhost";
	public static int PORT = 4321;
	public Socket socket;
	ObjectInputStream ois;
	public AdminClient() throws UnknownHostException, IOException{
		this.socket = new Socket(HOST,PORT);
		ois = getObjectInputStream(socket);
	}
    private PrintWriter getWriter(Socket socket) throws IOException{
        OutputStream socketOut=socket.getOutputStream();
        return new PrintWriter(socketOut,true);
    }
    private ObjectInputStream getObjectInputStream(Socket socket) throws IOException{
        InputStream socketIn=socket.getInputStream();
        return new ObjectInputStream(socketIn);
    }
    public boolean handle(String command) throws IOException, ClassNotFoundException{
		if (command.startsWith("shutdown")){
			String message = (String)ois.readObject();
			System.out.println(message);
			if(message.equals("shutdown")){
				System.out.println("Requesting shutdown order server");
				return true;
			}
		}else if(command.equals("exit")){
				return true;
		}else {
			System.out.println("Invalid Command");
			new Admin().printHelp();
		}
		return false;
	}
	public void request() throws ClassNotFoundException{
		try {
			PrintWriter pw=getWriter(socket);
			
			System.out.println("connecting to server");
			System.out.println("***************************************\n");
			String command;
			BufferedReader inBr = new BufferedReader(new InputStreamReader(new DataInputStream(System.in)));
			while (true) {
				System.out.println("input your command: ");
				command = inBr.readLine(); // 读取用户输入的字符串
				pw.println(command); // 将读取得字符串传给server
				if (handle(command))
					break;
			}
			
			System.out.println("Bye Bye");
		} catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                if(socket!=null)
                    socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
	}
	public static void main(String args[]) throws UnknownHostException, IOException, ClassNotFoundException {
		if (args.length == 1) {
			HOST = args[0];
		}else if(args.length==2){
			HOST = args[0];
			PORT = Integer.valueOf(args[1]);
		}
		new AdminClient().request();
	}
}